<template>

  <el-dialog
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :show-close="false"
    title="人脸登录"
    width="540px"
    append-to-body
  >
    <div class="face-box">

      <tracking-cam
        v-if="dialogVisible"
        ref="cam"
        :tracking="true"
        @tracked="handleTracked"/>

    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="danger" @click="handleClose">取 消</el-button>
    </div>

  </el-dialog>

</template>

<script>
import TrackingCam from '@/components/TrackingCam/index.vue'

export default {
  name: 'FaceLoginDialog',
  components: { TrackingCam },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    params: {
      type: Object,
      default: function() {
        return {}
      }
    },
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      faceInfo: {
        id: '',
        realName: '',
        idCard: ''
      }
    }
  },

  watch: {

    // 检测查询变化
    visible: {
      handler() {
        this.dialogVisible = this.visible
      },
      deep: true
    }
  },

  created() {
    this.dialogVisible = this.visible
  },

  methods: {

    // 关闭窗口
    handleClose() {
      this.$message.info('窗口已关闭，若要重新识别请刷新页面！')
      this.$emit('update:visible', false)
    },

    // 面部追踪成功
    handleTracked(base64) {
      this.$store.dispatch('user/faceLogin', { base64: base64 }).then(this.successBack).catch(this.failBack)
    },

    // 登录跳转
    successBack() {
      this.$message.success('登录成功，正在跳转..')
      setTimeout(() => {
        // 跳转到首页
        this.$emit('update:visible', false)
        // this.$router.push('/')
        window.close()
      }, 2000)
    },

    // 识别失败
    failBack() {
      this.$message.error('登录出现问题，请重试..')
      // 重新截屏
      this.$refs.cam.reTrack()
    }
  }
}
</script>

<style scoped>

.face-box{
  position: relative;
  width: 100%;
  height: auto;
}

</style>
